import { ref, watch } from 'vue'
import { defineStore } from 'pinia'
import { handleThemeChange } from '@/utils/changeTheme'

export const useMainStore = defineStore(
  'main',
  () => {
    const isDarkTheme = ref<boolean>(false)

    const isAppearanceTransition =
      // @ts-expect-error: Transition API
      document.startViewTransition &&
      !window.matchMedia(`(prefers-reduced-motion: reduce)`).matches

    const toggle = (event: MouseEvent) => {
      if (!isAppearanceTransition || !event) {
        isDarkTheme.value = !isDarkTheme.value
        return
      }

      const x = event.clientX
      const y = event.clientY

      const endRadius = Math.hypot(
        Math.max(x, innerWidth - x),
        Math.max(y, innerHeight - y)
      )

      // @ts-expect-error: Transition API
      const transition = document.startViewTransition(
        () => (isDarkTheme.value = !isDarkTheme.value)
      )

      transition.ready.then(() => {
        const clipPath = [
          `circle(0px at ${x}px ${y}px)`,
          `circle(${endRadius}px at ${x}px ${y}px)`
        ]
        document.documentElement.animate(
          {
            clipPath: isDarkTheme.value ? clipPath : [...clipPath].reverse()
          },
          {
            duration: 300,
            easing: 'ease-in',
            pseudoElement: isDarkTheme.value
              ? '::view-transition-new(root)'
              : '::view-transition-old(root)'
          }
        )
      })
    }

    watch(isDarkTheme, nv => {
      handleThemeChange(nv)
    })

    return {
      isDarkTheme,
      toggle
    }
  },
  {
    persist: {
      key: 'system-config',
      storage: localStorage,
      paths: ['isDarkTheme']
    }
  }
)
